package zm.irc.mqtt;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import zm.irc.cfg.WeechatConfig;
import zm.irc.ioc.annotation.AutoWired;
import zm.irc.ioc.annotation.Service;
import zm.irc.ioc.beanActoin.BeanPost;

@Service(isSinglet = true)
public class MyMqttClient implements BeanPost{
    private static final Logger log = Logger.getLogger(MyMqttClient.class);

    @AutoWired
    private MyMqttCfg mqttCfg;

    @AutoWired
    private WeechatConfig weechatSerct;
    private MqttClient mqttClient;

    public void send(String msg) {
        try {
            if(StringUtils.isEmpty(msg)){
                return;
            }
            MqttMessage message = new MqttMessage(msg.getBytes());
            message.setQos(this.mqttCfg.getQos());
            mqttClient.publish(this.mqttCfg.getTopic(), message);
        } catch (Exception e) {
            log.error("Send message error!", e);
        }
    }

    private void init() {
        try {
             this.mqttClient = new MqttClient(mqttCfg.getUrl(), mqttCfg.getClientId(), new MemoryPersistence());

            // 配置参数信息

            MqttConnectOptions options = new MqttConnectOptions();

            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，

            // 这里设置为true表示每次连接到服务器都以新的身份连接

            options.setCleanSession(true);

            // 设置用户名

            options.setUserName(this.mqttCfg.getUserName());

            // 设置密码

            options.setPassword(weechatSerct.getMqttpwd().toCharArray());

            // 设置超时时间 单位为秒

            options.setConnectionTimeout(this.mqttCfg.getConnectionTimeout());
            options.setAutomaticReconnect(true);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制

            options.setKeepAliveInterval(this.mqttCfg.getKeepAliveInterval());

            // 连接

            mqttClient.connect(options);

            // 订阅

           // mqttClient.subscribe(this.mqttCfg.getTopic());

            // 设置回调

           // mqttClient.setCallback(new MyMqttCallback());
        } catch (Exception e) {
            log.error("Mqtt Client Init error",e);
        }

    }

    @Override
    public Object post(Object bean) {
        this.init();
        return bean;
    }

}
